package com.example.cloud.service.basic.config.impl;

import com.example.cloud.dao.basic.config.ProcessTypeRepository;
import com.example.cloud.dao.mongdb.basic.config.MongoProcessTypeRepository;
import com.example.cloud.model.config.ProcessType;
import com.example.cloud.model.system.User;
import com.example.cloud.service.basic.config.ProcessTypeService;
import com.example.cloud.utils.BusinessUtil;
import com.example.cloud.utils.RequestUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;
import java.util.List;

/**
 * Created by wangtao on 2018/6/12.
 */
@Service
public class ProcessTypeServiceImpl implements ProcessTypeService {

    private static final Logger logger = Logger.getLogger(ProcessTypeServiceImpl.class);

    @PersistenceContext
    EntityManager em;

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    private ProcessTypeRepository processTypeRepository;

    @Autowired
    private MongoProcessTypeRepository mongoProcessTypeRepository;

    @Override
    @Transactional
    public void doSave(ProcessType record) {
        // 新增
        if(record.getId() == null){
            User loginUser = RequestUtil.getLoginUser();
            record.setUserId(loginUser.getId());
            record.setAccountId(loginUser.getAccountId());
            record.setOrganId(loginUser.getOrganId());
            record.setOrganName(loginUser.getOrganName());
        }
        BusinessUtil.appendRecord(record);
        // 物理保存
        processTypeRepository.save(record);
        // 同步缓存
        mongoProcessTypeRepository.save(record);
    }

    @Override
    @Transactional
    public void doDelete(List<Long> ids) {
        // 逻辑删除
        StringBuilder sql = new StringBuilder("update config_process_type set delete_flag = 1 where id in(:ids)");
        Query query = em.createNativeQuery(sql.toString());
        query.setParameter("ids", ids);
        query.executeUpdate();
        // 删除缓存
        mongoProcessTypeRepository.deleteByIdIn(ids);
    }

    @Override
    public void loadCache() {
        List<ProcessType> list = processTypeRepository.findAll();
        if(!list.isEmpty()){
            mongoProcessTypeRepository.save(list);
            logger.info("*******************处理类型已全部同步缓存*******************");
        }
    }
}
